package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWork;
import com.hmdp.utils.UserHolder;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private ISeckillVoucherService seckillVoucherService;

    @Autowired
    private RedisIdWork redisIdWork;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;

    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }


    // 线程池
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    // 启动时初始化
    @PostConstruct
    private void init() {
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }
    // 消息队列 stream
    private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024 * 1024);
    // 线程池任务
    private class VoucherOrderHandler implements Runnable {

        @Override
        public void run() {
            // 死循环，不断从阻塞队列中获取订单
            while (true) {

                try {
                    // 1.获取消息队列中的订单 XREADGROUP GROUP g1 c1 COUNT BLOCK 2000 stream.orders >
                    List<MapRecord<String, Object, Object>> list = redisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create("stream.orders", ReadOffset.lastConsumed())
                    );
                    // 2.判断消息获取是否成功
                    if(list == null || list.isEmpty()){
                        // 2.1 如果失败，则没有消息，进行下一次循环
                        continue;
                    }
                    // 3.解析消息中的订单数据
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> values = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(values, new VoucherOrder(), true);
                    // 3.1 成功，就可以创建订单
                    handleVoucherOrder(voucherOrder);
                    // 4.ACK确认 SACK stream.orders g1 id
                        redisTemplate.opsForStream().acknowledge("stream.orders", "g1", record.getId());
                } catch (Exception e) {
                    log.error("获取订单失败", e);
                    handlerPendingList();
                }

            }
        }

        private void handlerPendingList() {
            while (true) {

                try {
                    // 1.获取消息队列中的订单 XREADGROUP GROUP g1 c1 COUNT BLOCK 2000 stream.orders 0
                    List<MapRecord<String, Object, Object>> list = redisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create("stream.orders", ReadOffset.from("0"))
                    );
                    // 2.判断消息获取是否成功
                    if(list == null || list.isEmpty()){
                        // 2.1 没有异常消息
                        break;
                    }
                    // 3.解析消息中的订单数据
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> values = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(values, new VoucherOrder(), true);
                    // 3.1 成功，就可以创建订单
                    handleVoucherOrder(voucherOrder);
                    // 4.ACK确认 SACK stream.orders g1 id
                    redisTemplate.opsForStream().acknowledge("stream.orders", "g1", record.getId());
                } catch (Exception e) {
                    log.error("处理pendingList的异常", e);
                }

            }
        }
        private void handleVoucherOrder(VoucherOrder voucherOrder) {
            Long userId = voucherOrder.getUserId();
            // 创建锁对象，然后获取锁
            // SimpleRedisLock lock = new SimpleRedisLock(redisTemplate, "order:" + userId);

            RLock lock = redissonClient.getLock("lock:order:" + userId); // redisson 加锁

            // 获取锁 (也要改成redisson形式的)
            boolean tryLock = lock.tryLock();
            // 判断是否获取锁成功
            if (!tryLock) {
                // 获取锁失败，返回失败消息
                log.error("不允许重复下单");
                return;
            }
            try {
                // 获取代理对象（事务） -- 但是拿不到，因为基于子线程去做的，拿不到。
                //  IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
                proxy.createVoucherOrder(voucherOrder); // 线程的代理对象
            } catch (IllegalStateException e) {
                throw new RuntimeException(e);
            } finally {
                // 释放锁
                lock.unlock();
            }
        }
        // 阻塞队列
   /* private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024 * 1024);
    // 线程池任务
    private class VoucherOrderHandler implements Runnable {

        @Override
        public void run() {
            // 死循环，不断从阻塞队列中获取订单
            while (true) {
               // 1.获取队列中的订单
                try {
                    VoucherOrder voucherOrder = orderTasks.take();
                    // 2. 创建订单
                    handleVoucherOrder(voucherOrder);
                } catch (Exception e) {
                    log.error("获取订单失败", e);
                }

           }
        }*/
        // createVoucherOrder 方法，创建订单
        // 其实不用加锁也可以

    }


    private IVoucherOrderService proxy;

    /**、
     * 秒杀优惠券（lua优化）
     * @param voucherId
     * @return
     */

    @Override
    public Result seckillVoucher(Long voucherId) {
        // 获取用户id
        Long userId = UserHolder.getUser().getId();
        // 获取订单id
        long orderId = redisIdWork.nextId("order");
        // 1.执行lua脚本 发送订单到消息队列
        Long result = redisTemplate.execute(SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(),
                userId.toString(),
                String.valueOf(orderId));
        // 2.判断是否为0

        int r = result.intValue();
        if (r != 0){
            // 2.1. 不为0，代表没有购买资格
            return Result.fail(r == 1 ? "库存不足" : "不能重复下单");
        }
//        // 2.2. 为0，代表可以购买，把下单信息保存到阻塞队列
//
//        VoucherOrder voucherOrder = new VoucherOrder();
//        // 2.3. 订单id
//
//        voucherOrder.setId(orderId);
//        // 2.4. 用户id
//        userId = UserHolder.getUser().getId();
//        voucherOrder.setUserId(userId);
//        // 2.5. 代金券id
//        voucherOrder.setVoucherId(voucherId);
//        // 2.6. 创建阻塞队列
//        orderTasks.add(voucherOrder);
        // 3. 获取代理对象（事务）
         proxy = (IVoucherOrderService) AopContext.currentProxy();
        // 4.返回id
        return Result.ok(orderId);
    }

    /**
     * 秒杀优惠券
     *
     * @param voucherOrder
     * @return
     */
    // 因为涉及了两张表的操作，所以加上@Transactional注解
    @Override
 /*  public Result seckillVoucher(Long voucherId) {
        // 1. 查询优惠券
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
        System.out.println(voucher);
        // 2. 判断秒杀是否开始
        if(voucher.getBeginTime().isAfter(LocalDateTime.now())){
            // 秒杀尚未开始
            return Result.fail("秒杀尚未开始");
        }
        // 3. 判断秒杀是否结束
        if(voucher.getEndTime().isBefore(LocalDateTime.now())){
            // 秒杀已结束
            return Result.fail("秒杀已结束");
        }
        // 4. 判断库存是否充足
        if(voucher.getStock() < 1){
            // 库存不足
            return Result.fail("库存不足");
        }
        // 先获取锁，事务提交后释放锁
       Long userId = UserHolder.getUser().getId();
        // 创建锁对象，然后获取锁
       // SimpleRedisLock lock = new SimpleRedisLock(redisTemplate, "order:" + userId);

        RLock lock = redissonClient.getLock("lock:order:" + userId); // redisson 加锁
      /*  synchronized (userId.toString().intern()){
            // 获取当前的代理对象
            IVoucherOrderService proxy = (IVoucherOrderService)AopContext.currentProxy();
            return proxy.createVoucherOrder(voucherId);
        }


        // 获取锁 (也要改成redisson形式的)
        boolean tryLock = lock.tryLock();
        // 判断是否获取锁成功
        if (!tryLock) {
            // 获取锁失败，返回失败消息
            return Result.fail("不允许重复下单");
        }
        try {
            IVoucherOrderService proxy = (IVoucherOrderService)AopContext.currentProxy();
            return proxy.createVoucherOrder(voucherId);
        } catch (IllegalStateException e) {
            throw new RuntimeException(e);
        } finally {
            // 释放锁
            lock.unlock();
        }

    }*/

    /**
     *
     * @param voucherId
     * @return
     */
    @Transactional
    // synchronized 加在方法上，就变成线程安全的，但是效率不高（变成同步锁，效率低，串行执行）
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        // 先判断用户是否已经购买过该优惠券，再去扣减库存，然后下单
        // 5. 一人一单
        // 5.1. 查询订单
        Long userId = voucherOrder.getUserId();
        Long voucherId = voucherOrder.getVoucherId();
        // 加锁，防止多人同时下单(在用户)
        // toString(userId)来保证唯一性
        // 方法内部加锁，但是事务是有Spring去提交，释放锁，还是可能出现并发问题
        //synchronized (userId.toString())
            int count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
            // 5.2. 判断订单是否存在
            if (count > 0) {
                // 5.3. 存在，返回错误信息
                log.error("用户已购买过该优惠券");
                return ;
            }
            // 6. 扣减库存
            // 增加乐观锁 cas
            boolean success = seckillVoucherService.update()
                    .setSql("stock = stock - 1")
                    .eq("voucher_id", voucherId).gt("stock", 0)
                    .update();
            if (!success) {
                log.error("库存不足");
                return;
            }
            // 7. 创建订单

            save(voucherOrder);

    }

}
